<?php
/**
 *      会员中心 - 我的收藏夹
 *      [Jsen.net] (C)2013-2099 Jason Group Science and technology co., LTD.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      http://www.jsen.net
 *      tel:400-681-9511
*/
class PayController extends UserBaseController
{
    public function _initialize() {
        parent::_initialize();
        $this->db = model('pay');
        load('@.pay');
    }
    
    /* 账户余额充值 */
    public function init() {
        $SEO = seo(0,'账户余额充值');
        $userInfoList = getUserInfo($this->userid);//获取用户详细信息
    	$payment = getcache('payment', 'pay');
        if($payment['bank']['enabled']) $banks = explode(',', $payment['bank']['config']['banks']);
        if (IS_POST) {
            extract($_GET);
            if(empty($pay_code)) showmessage('请选择支付方式');
            if(!$payment[$pay_code]) showmessage('选择的支付方式不存在');
            if($pay_bank && !in_array($pay_bank, $banks)) showmessage('选择的支付网银错误');
            $total_fee = money($_GET['total_fee']);
            if ($total_fee == 0) showmessage('充值金额不能为0');
            if ($total_fee < C('lowest')) showmessage('单次充值金额必须大于等于'.C('lowest').'元');
            $product_info = array();
            $product_info['user_id'] = $this->userid;
            $product_info['code'] = $pay_code;
            $product_info['trade_sn'] = 'cz'.create_sn();
            $product_info['total_fee'] = $total_fee;
            $product_info['subject'] = '账户余额充值';
            $product_info['dateline'] = NOW_TIME;
            $product_info['pay_bank'] = $pay_bank;
			if($product_info['user_id']==0)showmessage('参数错误，请重试');
            $result = $this->db->update($product_info);
            if ($result) {
                libfile('pay_factory');
                $pay_factory =  new pay_factory($pay_code);
                $pay_factory->set_productinfo($product_info);
                if($pay_code=='wechat_qr' or $pay_code=='wechat_js'){
                    $trade_sn=$product_info['trade_sn'];
                    $jsApiData_json= $code_url=$pay_factory->get_code_url();

                   if(C("TMPL_THEME")=="wap"){
                    	C('DEFAULT_THEME','wap');
                    	//print_r($code_url);exit;
                    	include template('goods/wechat_wap_pay');
                    }else{
                    	include template('goods/wechat_recharge');
                    }
                }else{
               if($pay_code=="ecpss" or $pay_code=="ecpay"){
					$pay_factory->create();
					exit;
				}else{
					$pay_url = $pay_factory->get_code();	
					redirect($pay_url);
				}
             }
                
            } else {
                showmessage('充值请求创建失败，请稍候重试。');
            }
        } else {
			
			if($_GET["type"]==0 or $_GET["type"]==""){
				$sqlmap =array();
				$sqlmap['user_id'] = array('EQ',$this->userid);
				if($_GET["start"]!="" or $_GET["end"]!=""){
					$start = strtotime($_GET['start'].' 00:00:00');
					$end = strtotime($_GET['end'].' 23:59:59');
					$sqlmap['dateline'] =array('between',$start.','.$end);
				}
				$status=$_GET["status"];
				if($_GET["status"]==1)$_GET["status"]=0;
				if($_GET["status"]==2)$_GET["status"]=1;
				if(!($_GET["status"]==="")){
					if(isset($_GET["status"])){
						$sqlmap['status'] = $_GET["status"];
					}
				}
				if($sqlmap['status']==="")unset($sqlmap['status']);
				$pay_type=C("PAY_TYPE");
				$count =  M('pay')->where($sqlmap)->count();
				libfile('Page');
				$Page = new Page($count,8);
				$Page->listRows = 8;
				$list['list'] =  M('pay')->where($sqlmap)->page(PAGE,8)->order('id DESC')->select();
				$list['page'] = $Page->show();
				$list['c'] =$count;
				
			}else if($_GET["type"]==1){
				$sqlmap =array();
				$sqlmap['uid'] = array('EQ',$this->userid);
				$count =  M('user_withdraw')->where($sqlmap)->count();
				libfile('Page');
				$Page = new Page($count,8);
				$status=$_GET["status"];
				if(!($_GET["status"]==="")){
					if(isset($_GET["status"])){
						$sqlmap['withdraw_status'] = $_GET["status"];
					}
				}
				$Page->listRows = 8;
				$list['list'] =  M('user_withdraw')->where($sqlmap)->page(PAGE,8)->order('id DESC')->select();
				$list['page'] = $Page->show();
				$list['c'] =$count;
				
			}else{
				 $applie = defined('IS_MOBILE') ? 'wap' : 'pc';
				  foreach ($payment as $code => $pay) {
					  //print_r($$pay);云班客
					  if(C("TMPL_THEME")=="wap"){
							  if($code=="ecpay") unset($payment[$code]);continue;
							  if($code=="wechat_qr") unset($payment[$code]);continue;
					  }
						  if($code=="ecpay"){}else{
							  if(!$pay['enabled'] || !$pay['isonline'] || !preg_match("/".$applie."/",$pay['applies']) ) {
								  unset($payment[$code]);continue;
							  }
						  }
					  $pay['config'] = json_decode($pay['config'], TRUE);
					  $payment[$code] = $pay;
				  }
				$banks = (in_array('bank',C('pays'))) ? $banks : FALSE;
			}
            include template('pay');
        }
    }
	public function paylog() {
		$SEO = seo(0,'账户充值记录');
		$sqlmap =array();
        $sqlmap['user_id'] = array('EQ',$this->userid);
        if($_GET["start"]!="" or $_GET["end"]!=""){
			$start = strtotime($_GET['start'].' 00:00:00');
			$end = strtotime($_GET['end'].' 23:59:59');
			$sqlmap['dateline'] =array('between',$start.','.$end);
		}
		$status=$_GET["status"];
		if($_GET["status"]==1)$_GET["status"]=0;
		if($_GET["status"]==2)$_GET["status"]=1;
		if(!($_GET["status"]==="")){
			if(isset($_GET["status"])){
				$sqlmap['status'] = $_GET["status"];
			}
		}
		if($sqlmap['status']==="")unset($sqlmap['status']);
		$pay_type=C("PAY_TYPE");
		$count =  M('pay')->where($sqlmap)->count();
		libfile('Page');
		$Page = new Page($count,8);
        //$Page->setConfig('prev','');
       // $Page->setConfig('next','');
        //$Page->setConfig('theme','%upPage% %linkPage% %downPage%');
        $Page->listRows = 8;
		$list['list'] =  M('pay')->where($sqlmap)->page(PAGE,8)->order('id DESC')->select();
		$list['page'] = $Page->show();
        $list['c'] =$count;
        include template('paylog');
    }
    /* 充值成功 */
    public function pay_success(){
        showmessage('充值成功！请查收账户余额！',U('User/Index/index'),1);
    }

    /* 检测是否支付成功 */
    public function is_success() {
        $status = $this->db->where(array('user_id' => $this->userid))->order('id DESC')->getField('status');
        exit(json_encode(array('status' => $status)));
    }
    public function get_recharge_status($trade_sn) {
        $sqlmap=array();
        $sqlmap['user_id']=$this->userid;
        $sqlmap['trade_sn']=$trade_sn;
        $status = $this->db->where($sqlmap)->order('id DESC')->getField('status');
        exit(json_encode(array('status' => $status)));
    }
	
	/* 提现 */
    public function withdraw() {
		$SEO = seo(0,'账户余额提现');
		//$old_time=time()-(86400*700);
		$sqlmap =array();
        $sqlmap['uid'] = array('EQ',$this->userid);
		$user=M('user')->where($sqlmap)->count();
		$last=strtotime('-7 days');
		$next=time();
		$nownum=M("user_withdraw")->where("uid=".$this->userid." and (withdraw_status=1 or withdraw_status=0) and add_time>".$last)->count();
        include template('withdraw');
    }
	 public function withdrawlog() {
		$SEO = seo(0,'账户提现记录');
		$sqlmap =array();
        $sqlmap['uid'] = array('EQ',$this->userid);
		$count =  M('user_withdraw')->where($sqlmap)->count();
		libfile('Page');
		$Page = new Page($count,8);
        //$Page->setConfig('prev','');
       // $Page->setConfig('next','');
		$status=$_GET["status"];
		if(!($_GET["status"]==="")){
			if(isset($_GET["status"])){
				$sqlmap['withdraw_status'] = $_GET["status"];
			}
		}
       // $Page->setConfig('theme','%upPage% %linkPage% %downPage%');
        $Page->listRows = 8;
		$list['list'] =  M('user_withdraw')->where($sqlmap)->page(PAGE,8)->order('id DESC')->select();
		$list['page'] = $Page->show();
        $list['c'] =$count;
        include template('withdrawlog');
    }
	 public function dowithdraw() {
		extract($_GET);
		$pinpass=$_GET["pinpass"];
		$u_info =model('user')->where(array('id' => $this->userid))->find();
		if($u_info["true_name"]=="")showmessage('您还没有填写真实姓名！');
		if($u_info["banknum"]=="")showmessage('您还没有填写提现银行信息！');
		if($pinpass=="")showmessage('二级密码不能为空');
		if(md5($pinpass)!=$u_info["pinpass"])showmessage('二级密码错误，请重新输入');
		$last=strtotime('-7 days');
		$next=time();
		$nownum=M("user_withdraw")->where("uid=".$this->userid." and (withdraw_status=1 or withdraw_status=0) and add_time>".$last)->count();
		if ($nownum >= C('withdrawnum')) showmessage('每周仅限'.C("withdrawnum").'次');
		if ($total_fee > $u_info['user_money']) showmessage('您的余额不足以提现！');
		$total_fee = money($_GET['total_fee']);
		if ($total_fee == 0) showmessage('提现金额不能为0');
		if ($total_fee < C('withdraw')) showmessage('单次提现金额必须大于等于'.C("withdraw").'元');
		$mod_money=fmod($total_fee,100);
		if($mod_money>0)showmessage('提现金额只能为100的倍数');
		
		model("user")->startTrans();
		$is_u=model("user")->where(array("id" => $this->userid))->setDec("user_money", $total_fee);
		$is_c=model("user")->where(array("id" => $this->userid))->setInc("freeze_money", $total_fee);
		$money_info = model("user")->find($this->userid);
		$data = array();
		$data["user_id"] = $this->userid;
		$data["money"] = -$total_fee;
		$data["msg"] = "提现扣除资金";
		$data["dateline"] = NOW_TIME;
		$data["type"] = 5;
		$data["user_money"] = $money_info["user_money"];
		$data["freeze_money"] = $money_info["freeze_money"];
		$is_m=model("user_moneylog")->add($data);
		$product_info = array();
		$product_info["uid"] = $this->userid;
		$product_info["withdraw_money"] = $total_fee;
		$product_info["withdraw_fee"] = (C("withdrawfee") * $total_fee) / 1000;
		$product_info["withdraw_status"] = 0;
		$product_info["add_time"] = NOW_TIME;
		$result = m("user_withdraw")->add($product_info);
		
		if ($is_u!==false and $is_m!==false and $result!==false and $result!==is_c){ 
			model("user")->commit();
			showmessage("提现申请提交成功，等待平台处理");
		
		}else{
			model("user")->rollback();
			showmessage("提现失败");

		}
		
    }
}